import sha256 from '../../utils/sha256.js'
import { encode as base64_encode, decode as base64_decode } from '../../utils/base64.js'


// 没有实力搓个JWT出来，随便写啦

// 密钥就随便放啦，太麻烦了
const flagStr = "i-like-sleep"
const LwtKey = "sleepppppppppppppppppppppppppppppppppppppppp"


class parser {

    static claims = null
    static signature = "ilikesleep"
    
    static setSignature(key) {
        parser.signature = key
        return parser
    }

    static getClamins() {
        return parser.claims
    }

    static parse(token) {

        // 随便解密一下啦
        const arr = String(token).split(".")
        if (arr.length != 3) {
            throw new Error("token is error")
        }

        

        let str = arr[0] + " - xixi - " + arr[1]

        let flag = str.length
        for (let i = 0; i < flagStr.length; i ++) {
            flag ^= flagStr.charCodeAt(i)
        }

        str = base64_encode(sha256(str + " so = " + flag + " " + LwtKey))


        if (str != arr[2]) {
            // 令牌不正确
            throw new Error("token is invalid")
        }

        try {
            parser.claims = JSON.parse(base64_decode(arr[1]))
        }catch(e) {
            throw new Error("token data is invalid")
        }

        if (!parser.claims.exp || parser.claims.exp <= new Date().valueOf()) {
            throw new Error("token has exp")
        }
        
        return parser
    }

}

class builder {

    static exp = 0
    static claims = null
    static signature = "ilikesleep"
    
    static setSignature(key) {
        builder.signature = key
        return builder
    }

    static setClaims(claims) {
        builder.claims = claims
        return builder
    }

    static setExpiration(time) {
        builder.exp = time
        return builder
    }

    static compact() {
        const obj = Object.assign({
            exp: builder.exp
        }, builder.claims)

        const header =  base64_encode(JSON.stringify({
            alg: 'Lalala',
            type: 'Lwt'
        }))

        const body = base64_encode(JSON.stringify(obj))


        let str = header + " - xixi - " + body

        let flag = str.length
        for (let i = 0; i < flagStr.length; i ++) {
            flag ^= flagStr.charCodeAt(i)
        }

        const verify = base64_encode(sha256(str + " so = " + flag + " " + LwtKey))



        return header + "." + body + "." + verify
        
    }

}

export default {
    parser,
    builder
}